package com.song.boot.springstudy.ms.szjz.al5;

import java.util.concurrent.*;

public class RequestProcessor {
    // 每秒处理5个请求，所以请求之间的间隔应为200毫秒
    private static final long REQUEST_INTERVAL_MS = 200;
    
    // 使用阻塞队列存储待处理的请求
    private final BlockingQueue<Runnable> requestQueue = new LinkedBlockingQueue<>();
    
    // 创建单线程池来处理请求，保证顺序执行
    private final ExecutorService processor = Executors.newSingleThreadExecutor();
    
    public RequestProcessor() {
        startProcessing();
    }
    
    // 提交请求到队列
    public void submitRequest(Runnable request) {
        try {
            requestQueue.put(request);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("请求提交被中断: " + e.getMessage());
        }
    }
    
    // 开始处理请求，控制速率
    private void startProcessing() {
        processor.execute(() -> {
            try {
                while (!Thread.currentThread().isInterrupted()) {
                    // 从队列中获取请求
                    Runnable request = requestQueue.take();
                    
                    // 处理请求
                    request.run();
                    
                    // 控制速率，每秒最多处理5个
                    Thread.sleep(REQUEST_INTERVAL_MS);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("请求处理器被中断");
            }
        });
    }
    
    // 关闭处理器
    public void shutdown() {
        processor.shutdown();
        try {
            if (!processor.awaitTermination(5, TimeUnit.SECONDS)) {
                processor.shutdownNow();
            }
        } catch (InterruptedException e) {
            processor.shutdownNow();
        }
    }
    
    // 测试示例
    public static void main(String[] args) {
        RequestProcessor processor = new RequestProcessor();
        
        // 提交10个测试请求
        for (int i = 0; i < 10; i++) {
            final int requestId = i;
            processor.submitRequest(() -> {
                System.out.println("处理请求 " + requestId + " - 时间: " + System.currentTimeMillis());
            });
        }
        
        // 等待所有请求处理完成后关闭
        new Thread(() -> {
            try {
                // 等待足够长的时间让所有请求处理完成
                Thread.sleep(10 * 1000);
                processor.shutdown();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }
}
